package qcmPlus.tests.java;

import java.io.FileInputStream;
import java.util.ArrayList;

import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.hibernate.Session;

import qcmPlus.tools.HibernateUtil;

public abstract class AbstractTest {
	private IDatabaseTester databaseTester;
	private IDataSet databaseDataset;
	
	public AbstractTest() throws Exception{
		
			databaseTester = new JdbcDatabaseTester("com.mysql.jdbc.Driver",
					"jdbc:mysql://localhost/qcmplus", "root", "");

			IDatabaseConnection connection = databaseTester.getConnection();
			databaseDataset = connection.createDataSet();

	}
	protected IDataSet getDataSet(String url) throws Exception {
		FileInputStream fileInput = new FileInputStream(url);
		IDataSet dataset = new FlatXmlDataSet(fileInput);
		return dataset;
	}

	protected void initial(String url) throws Exception {
		IDataSet dataset = getDataSet(url);
		databaseTester.setDataSet(dataset);
		databaseTester.onSetup();
	}
	

	protected void clean(String nomTable) throws Exception {
		Session s = HibernateUtil.currentSession();
		String query = "from "+nomTable+" order by id";
		ArrayList<?> list = (ArrayList<?>) s
				.createQuery(query).list();
		for (Object objet : list) {
			s.delete(objet);
		}
	}
	public IDataSet getDatabaseDataset() {
		return databaseDataset;
	}
	
	public ITable getActualTable(String nomTable) throws Exception {
		
		return databaseDataset.getTable(nomTable);
	}
	
	public ITable getExpectedTable(IDataSet expectedDataSet, String nomTable) throws Exception {
		
		return expectedDataSet.getTable(nomTable);
	}
	
	public IDataSet getExpectedDataset(String url) throws Exception {
		
		return getDataSet(url);
	}
	
}
